{
 "metadata": {
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''百度飞桨Hello, paddle!'''\n",
    "# 传统程序：给定规则和输入，计算得到输出\n",
    "# 机器学习程序：给定输入和样本，自动学习规则，然后利用学习到的规则计算得到输出\n",
    "\n",
    "import paddle\n",
    "import numpy as np\n",
    "\n",
    "print('paddle ' + paddle.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 输出y和输入x具有线性关系：y=2*x+5\n",
    "# 下面使用飞桨搭建一个线性模型学习出w, b的值\n",
    "w, b = 2, 5\n",
    "# x中的每一行是一个样本\n",
    "x = paddle.to_tensor([[1.], [4.], [5.], [9.], [8.], [10.], [12.]])\n",
    "y = x * w + b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 开始学习前的参数值\n",
    "model = paddle.nn.Linear(in_features=1, out_features=1)\n",
    "w_before_opt = model.weight.numpy().item()\n",
    "b_before_opt = model.bias.numpy().item()\n",
    "print(\"初始化w的值: {}\".format(w_before_opt))\n",
    "print(\"初始化b的值: {}\".format(b_before_opt))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义损失函数与优化方法，开始训练\n",
    "mse_loss = paddle.nn.MSELoss()\n",
    "sgd_optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters = model.parameters())\n",
    "total_epoch = 12000\n",
    "for i in range(total_epoch):\n",
    "    y_predict = model(x)\n",
    "    loss = mse_loss(y_predict, y)\n",
    "    loss.backward()\n",
    "    sgd_optimizer.step()\n",
    "    sgd_optimizer.clear_grad()\n",
    "    if i%1000 == 0:\n",
    "        print(\"epoch {} loss {}\".format(i, loss.numpy()))\n",
    "\n",
    "print(\"finished training， loss {}\".format(loss.numpy()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 查看训练得到的参数\n",
    "w_after_opt = model.weight.numpy().item()\n",
    "b_after_opt = model.bias.numpy().item()\n",
    "\n",
    "print(\"学习到w的值: {}\".format(w_after_opt))\n",
    "print(\"学习到b的值: {}\".format(b_after_opt))\n",
    "print(\"Hello, paddle!\")"
   ]
  }
 ]
}